<template>
  <div class="knowledge-update-optimization">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="新案例自动导入" name="import">
        <div class="section">
          <h3>新案例自动导入频率设置</h3>
          <el-form :inline="true" @submit.native.prevent>
            <el-form-item label="扫描频率">
              <el-select v-model="importFrequency" placeholder="请选择频率" @change="saveFrequency">
                <el-option v-for="item in frequencyOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="simulateImport">模拟扫描并导入新案例</el-button>
        </div>
        <div class="section">
          <h3>知识图谱故障关联关系更新</h3>
          <el-table :data="relations" style="width: 100%">
            <el-table-column prop="fault1" label="故障1" />
            <el-table-column prop="fault2" label="故障2" />
            <el-table-column prop="association" label="关联度" />
            <el-table-column prop="change" label="本次提升" />
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="机器学习优化" name="ml">
        <div class="section">
          <h3>优化目标选择</h3>
          <el-select v-model="mlTarget" placeholder="请选择优化目标" @change="filterLowConfidence">
            <el-option v-for="item in mlTargets" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="section">
          <h3>低置信度知识（待审核）</h3>
          <el-table :data="lowConfidenceRules" style="width: 100%">
            <el-table-column prop="rule" label="规则描述" />
            <el-table-column prop="accuracy" label="准确率" />
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === '待审核'" type="warning">待审核</el-tag>
                <el-tag v-else type="success">已优化</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status === '待审核'" type="primary" size="mini" @click="approveRule(scope.$index)">审核通过</el-button>
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
// 使用Element UI组件库
const LOCAL_KEY_FREQ = 'knowledge_import_frequency';
const LOCAL_KEY_RELATIONS = 'knowledge_relations';
const LOCAL_KEY_RULES = 'knowledge_rules';

// mock数据
const defaultRelations = [
  { fault1: '齿轮箱漏油', fault2: '密封件老化', association: '60%', change: '+0%' },
  { fault1: '电机过热', fault2: '轴承磨损', association: '45%', change: '+0%' },
];
const defaultRules = [
  { rule: '齿轮箱漏油 ← 密封件老化', accuracy: 65, status: '待审核' },
  { rule: '电机过热 ← 轴承磨损', accuracy: 72, status: '已优化' },
  { rule: '振动异常 ← 地脚松动', accuracy: 68, status: '待审核' },
];

export default {
  name: 'KnowledgeUpdateOptimization',
  data() {
    return {
      activeTab: 'import',
      importFrequency: '',
      frequencyOptions: [
        { label: '每小时', value: '1h' },
        { label: '每3小时', value: '3h' },
        { label: '每天', value: '24h' },
      ],
      relations: [],
      mlTarget: '',
      mlTargets: [
        { label: '提高规则准确率', value: 'accuracy' },
        { label: '提升召回率', value: 'recall' },
      ],
      rules: [],
      lowConfidenceRules: [],
    };
  },
  created() {
    this.loadFrequency();
    this.loadRelations();
    this.loadRules();
    this.filterLowConfidence();
  },
  methods: {
    // 频率设置本地存储
    saveFrequency() {
      localStorage.setItem(LOCAL_KEY_FREQ, this.importFrequency);
    },
    loadFrequency() {
      const freq = localStorage.getItem(LOCAL_KEY_FREQ);
      this.importFrequency = freq || '1h';
    },
    // 关联关系本地存储
    loadRelations() {
      const rel = localStorage.getItem(LOCAL_KEY_RELATIONS);
      this.relations = rel ? JSON.parse(rel) : JSON.parse(JSON.stringify(defaultRelations));
    },
    saveRelations() {
      localStorage.setItem(LOCAL_KEY_RELATIONS, JSON.stringify(this.relations));
    },
    // 规则本地存储
    loadRules() {
      const rules = localStorage.getItem(LOCAL_KEY_RULES);
      this.rules = rules ? JSON.parse(rules) : JSON.parse(JSON.stringify(defaultRules));
    },
    saveRules() {
      localStorage.setItem(LOCAL_KEY_RULES, JSON.stringify(this.rules));
    },
    // 模拟导入新案例并更新知识图谱
    simulateImport() {
      // 假设扫描到一个新案例：齿轮箱漏油与密封件老化关联度提升20%
      let updated = false;
      this.relations = this.relations.map(item => {
        if (item.fault1 === '齿轮箱漏油' && item.fault2 === '密封件老化') {
          const oldValue = parseInt(item.association);
          item.association = (oldValue + 20) + '%';
          item.change = '+20%';
          updated = true;
        } else {
          item.change = '+0%';
        }
        return item;
      });
      if (!updated) {
        this.relations.push({ fault1: '齿轮箱漏油', fault2: '密封件老化', association: '20%', change: '+20%' });
      }
      this.saveRelations();
      this.$message.success('新案例导入并更新知识图谱成功！');
    },
    // 机器学习优化：筛选低置信度知识
    filterLowConfidence() {
      // 这里只模拟“提高规则准确率”目标，筛选准确率<70%的规则
      if (this.mlTarget === 'accuracy' || !this.mlTarget) {
        this.lowConfidenceRules = this.rules.filter(r => r.accuracy < 70);
      } else {
        this.lowConfidenceRules = [];
      }
    },
    // 审核通过后自动优化权重
    approveRule(idx) {
      const rule = this.lowConfidenceRules[idx];
      // 提高权重，模拟准确率提升到80%
      const ruleIdx = this.rules.findIndex(r => r.rule === rule.rule);
      if (ruleIdx !== -1) {
        this.rules[ruleIdx].accuracy = 80;
        this.rules[ruleIdx].status = '已优化';
      }
      this.saveRules();
      this.filterLowConfidence();
      this.$message.success('审核通过，已自动优化权重！');
    },
  },
};
</script>

<style scoped>
.knowledge-update-optimization {
  padding: 24px;
}
.section {
  margin-bottom: 32px;
}
</style>
